<script setup>
import { EmailOutlined, LockOpenOutlined } from "@vicons/material";
import { useMessage, useLoadingBar } from "naive-ui";
import { noteBaseRequest } from "@/request/noterequset";

import { ref } from "vue";

const message = useMessage();
const loadingBar = useLoadingBar();
const emits = defineEmits(["changeStep"]);
const loading = ref(false);

//注册表单值
const registerFormValue = ref({
  email: "",
  vc: "",
  trim: false,
});
//注册表单验证规则
const registerFormRules = {
  email: [
    {
      required: true,
      message: "请输入邮箱号",
      trigger: ["input", "blur"],
    },
    {
      key: "mail",
      message: "请正确输入邮箱号",
      trigger: ["input", "blur"],
      validator: (rule, value) => {
        return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value);
      },
    },
  ],
  //blur失去焦点  vc验证
  vc: {
    required: true,
    message: "请输入验证码",
    trigger: ["input", "blur"],
  },
  trim: {
    message: "请认真阅读app条款与协议",
    trigger: "change",
    validator: (rule, value) => {
      return value;
    },
  },
};
//注册表单引用对象
const registerFormRef = ref(null);
//去注册
const toRegister = (e) => {
  e.preventDefault();
  registerFormRef.value?.validate(async (errors) => {
    if (!errors) {
      const vcKey = emailVcKey.value;
      if (!vcKey) {
        throw message.error("请先获取验证码");
      }
      const vc_email = vcKey.split(":")[1];
      const email = registerFormValue.value.email;
      if (email !== vc_email) {
        throw message.error("注册邮箱号发生改变，请重新获取");
      }
      loadingBar.start();
      loading.value = true;
      const { data: responseData } = await noteBaseRequest
        .post("/user/register/email", {
          email: registerFormValue.value.email,
          vc: registerFormValue.value.vc,
          vcKey,
        })
        .catch(() => {
          //发送404，500，400.....
          message.error("发送注册请求失败");
          loadingBar.error();

          setTimeout(() => {
            loading.value = false;
          }, 1500);
          throw "发送注册请求失败";
        });
      //得到服务器返回数据进行处理
      console.log(responseData);
      if (responseData.success) {
        loadingBar.finish();
        message.success(responseData.message);
        emits("changeStep", 3);
      } else {
        loadingBar.error();
        message.error(responseData.message);

        setTimeout(() => {
          loading.value = false;
        }, 1500);
      }
    }
  });
};
//按钮状态
const btnCountDown = ref({
  text: "获取验证码",
  time: 60,
  disabled: false, //是否禁用按钮
  clock: null,
});
//按钮倒计时
const buttonCountDown = () => {
  btnCountDown.value.clock = setInterval(() => {
    if (btnCountDown.value.time === 1) {
      resetButtonCountDownStatus();
    } else {
      btnCountDown.value.disabled = true; //禁用按钮
      btnCountDown.value.time--; //时间递减
      btnCountDown.value.text = btnCountDown.value.time + "重新获取"; //按钮显示文本
    }
  }, 1000);
};
//重置按钮
const resetButtonCountDownStatus = () => {
  clearInterval(btnCountDown.value.clock);
  btnCountDown.value.text = "获取验证码";
  btnCountDown.value.time = 60;
  btnCountDown.value.disabled = false;
};
//获取验证码
const emailVcKey = ref("");
const getEmailVC = () => {
  registerFormRef.value?.validate(
    async (errors) => {
      if (!errors) {
        buttonCountDown(); //邮箱格式正确 按钮倒计时
        loadingBar.start();
        const { data: responseData } = await noteBaseRequest
          .get("/mail/register/vc", {
            params: { email: registerFormValue.value.email },
          })
          .catch(() => {
            //发送404，500，400.....
            message.error("发送验证码请求失败");
            loadingBar.error();
            throw "发送验证码请求失败";
          });
        //得到服务器返回数据进行处理
        console.log(responseData);
        if (responseData.success) {
          loadingBar.finish();
          emailVcKey.value = responseData.data;
          message.success(responseData.message);
        } else {
          loadingBar.error();
          message.error(responseData.message);
        }
      }
    },
    (rule) => {
      return rule?.key === "mail";
    }
  );
};
</script>

<template>
  <n-card>
    <!--          前往登录-->
    <n-space justify="space-between" align="center">
      <h2>注册</h2>
      <n-text depth="3">
        已经有账号？
        <n-button text="true" type="info" @click="emits('changeStep', 1)">
          前往登录
        </n-button>
      </n-text>
    </n-space>
    <!--           注册表单-->
    <n-form
      :model="registerFormValue"
      :rules="registerFormRules"
      ref="registerFormRef"
    >
      <!--          path明确验证规则 first只显示第一个错误-->
      <n-form-item label="邮箱号码" path="email" first>
        <n-input
          placeholder="请输入邮箱号码！"
          v-model:value="registerFormValue.email"
        >
          <template #prefix>
            <n-icon :component="EmailOutlined" />
          </template>
        </n-input>
      </n-form-item>
      <n-grid :cols="2" :x-gap="24">
        <n-form-item-gi label="验证码" path="vc">
          <n-input
            placeholder="请输入验证码！"
            v-model:value="registerFormValue.vc"
          />
        </n-form-item-gi>
        <n-form-item-gi>
          <n-button
            block
            secondary
            type="success"
            :disabled="btnCountDown.disabled"
            @click="getEmailVC"
          >
            {{ btnCountDown.text }}
          </n-button>
        </n-form-item-gi>
      </n-grid>
      <n-form-item :show-label="false" path="trim">
        <n-checkbox v-model:checked="registerFormValue.trim"
          >是否同意该
        </n-checkbox>
        <n-button text type="info"> 《条款与协议》 </n-button>
      </n-form-item>
      <n-form-item :show-label="false">
        <n-button :disabled="loading" block type="success" @click="toRegister">
          注册
        </n-button>
      </n-form-item>
    </n-form>
  </n-card>
</template>
